<template>
	<div>
		<el-card class="box-card">
			<el-form :inline="true" :model="tableParams" class="user-search">
				<el-form-item label="">
					<el-input size="small" v-model="tableParams.name" placeholder="输入"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button size="small" type="primary" icon="el-icon-search" @click="search" round>搜索</el-button>
					<el-button size="small" type="primary" icon="el-icon-plus" @click="handleInsert"
						round>添加</el-button>
					<!-- <el-button size="small" type="primary" @click="handleunit()">部门设置</el-button> -->
				</el-form-item>
			</el-form>
		</el-card>


		<el-table :data="tableData" style="width: 100%">
			<el-table-column prop="name" label="名称" width="120">
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="300">
			</el-table-column>
			<el-table-column prop="sstatus" label="状态" width="120">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.s_status" :value="scope.row.sstatus" />
				</template>
			</el-table-column>
			<el-table-column align="center" label="操作" min-width="300">
				<template slot-scope="scope">
					<el-button size="mini" type="success" icon="el-icon-edit" @click="assignPermissions(scope.row)"
						round>设置权限</el-button>
					<el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"
						round>编辑</el-button>
					<el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"
						round>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div>
			<!-- 使用分页组件 -->
			<Pagination :tableParams="tableParams" @size-change="onPageSizeChange"
				@current-change="onCurrentPageChange" />
		</div>

		<!-- 用户导入对话框 -->
		<el-dialog :title="title" :visible.sync="iustatus">
			<el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
				<el-form-item label="角色" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm('form')">立即创建</el-button>
					<el-button @click="resetForm('form')">重置</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 操作角色权限 -->
		<el-dialog :visible.sync="PermissionsFormVisible" width="30%" @click='closeDialog("edit")'>
			<el-form label-width="120px" :model="permissionsForm" ref="editForm" :rules="rules">
				<el-form-item label="菜单" prop="name">

					<el-tree :data="menuOptions" show-checkbox node-key="id" :expand-on-click-node="true"
						:check-strictly="checkStrictly" highlight-current :default-checked-keys="menuDefKeys"
						ref="menutree" :props="treePropsmenu"
						@check="(nodeObj, SelectedObj)=>currentChecked(nodeObj, SelectedObj,'menu')" current-node-key>
					</el-tree>

				</el-form-item>
				<el-form-item label="权限" prop="name">

					<el-tree :data="permissionOptions" show-checkbox node-key="id" :expand-on-click-node="true"
						:check-strictly="checkStrictly" highlight-current :default-checked-keys="permissionDefKeys"
						@check="(nodeObj, SelectedObj)=>currentChecked(nodeObj, SelectedObj,'permission')"
						@check-change="getCurrentNode" ref="permissiontree" :props="treeProps" current-node-key>
					</el-tree>

				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click='PermissionsFormVisible = false' round>取消</el-button>
				<el-button size="small" type="primary" :loading="loading" class="title"
					@click="submitPermissionForm('permissionForm')" round>
					保存</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	import {
		list,
		getById,
		insert,
		update,
		deleteIds,
		getMenu,
		getPermissions
	} from '@/api/system/role';
	export default {
		dicts: ['s_status', 'sex'],
		data() {
			return {
				iustatus: false,
				title: '',
				upstatus: false,
				//修改编辑
				form: {},
				rules: {
					name: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}]
				},
				//表格数据
				tableData: [],
				//分页
				tableParams: {
					pageNum: 1, // 当前页码
					pageSize: 20, // 每页显示的数量
					total: 100, // 数据总条数
					name: ""
				},

				treeProps: {
					label: "name",
					children: "children"
				},
				treePropsmenu: {
					label: "name",
					children: "children"
				},
				PermissionsFormVisible: false,
				// 默认选中节点id数组
				menuDefKeys: [],
				permissionDefKeys: [],
				menuOptions: [],
				permissionOptions: [],
				//选择节点
				menuDefKeys: [],
				permissionDefKeys: [],
				checkStrictly: false,
				loading: false, //是显示加载
				permissionsForm: {
					id: 0,
					menuIds: [],
					premisIds: [],
				},
			}

		},
		created() {
			this.getDatailist();
		},
		methods: {
			//查询
			search() {
				this.getDatailist();
			},
			//编辑
			handleEdit(row) {
				this.iustatus = true;
				this.upstatus = true;
				this.title = "修改";
				this.form = row;
			},
			//删除
			handleDelete(row) {
				this.$confirm('此操作将永久删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteIds(row.id)
						.then((res) => {
							if (res.code == 200) {
								this.getDatailist();
							} else {
								this.logining = false
							}
						})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//添加
			handleInsert() {
				this.iustatus = true;
				this.title = "添加";
				this.form = {};

			},

			assignPermissions(row) {
				this.PermissionsFormVisible = true;
				this.getmenudata();
				this.getpermissiondata();
				this.permissionsForm.id = row.id;

				if (row && typeof row === 'object') {
					let menuIds = row.menuIds;
					let permisIds = row.premisIds;

					// 将字符串转换为数组，如果是字符串的话
					if (typeof menuIds === 'string') {
						menuIds = row.menuIds.split(",");
					}

					if (typeof permisIds === 'string') {
						permisIds = row.premisIds.split(",");
					}
					let that = this;
					setTimeout(function() {
						permisIds.forEach(value => {
							that.$refs.permissiontree.setChecked(value, true, false);
						});
						menuIds.forEach(value => {
							that.$refs.menutree.setChecked(value, true, false);
						});
					}, 200);
				} else {
					console.error('Invalid row object provided.');
				}
			},

			// 获取菜单数据方法
			getmenudata() {
				this.loading = true
				getMenu().then(res => {
					if (res.code == 200) {
						this.loading = false
						this.menuOptions = res.data
						menuOptions.map((item) => {
							this.menuDefKeys.push(item.id)
						})
						this.checkStrictly = true, //给树节点赋值之前，先设置为true
							this.$nextTick(() => {
								// setTimeout(() => {
								//渲染
								// this.menuDefKeys = this.getArray(this.menuOptions, true, []);
								this.$refs.menutree.setCheckedNodes(this.menuDefKeys); //给树节点赋值
								this.checkStrictly = false; //赋值完成后设置为false
								// }, 0)
							})
						this.menupageparm.total = res.data.data.total
					} else {

					}
				}).catch((error) => {
					this.logining = false
				});
			},

			// 获取权限数据方法
			getpermissiondata() {
				this.loading = true
				getPermissions().then(res => {
					if (res.code == 200) {
						this.loading = false
						this.permissionOptions = res.data
						menuOptions.map((item) => {
							this.permissionDefKeys.push(item.id)
						})

						// permissiontree
						this.checkStrictly = true, //给树节点赋值之前，先设置为true
							this.$nextTick(() => {
								// setTimeout(() => {
								//渲染
								this.$refs.permissiontree.setCheckedNodes(this.permissionDefKeys); //给树节点赋值
								this.checkStrictly = false; //赋值完成后设置为false
								// }, 0)
							})
					} else {

					}
				}).catch((error) => {
					this.logining = false
				});
			},
			currentChecked(nodeObj, SelectedObj, value) {
				if (value == 'menu') {
					this.permissionsForm.menuIds = SelectedObj.checkedKeys
				} else {
					this.permissionsForm.premisIds = SelectedObj.checkedKeys
				}
			},
			getCurrentNode(data) {
				var getCurrentNode = this.$refs.permissiontree.getCurrentNode()
			},
			submitPermissionForm(permissionsForm) {
				//判断是否拥有权限和菜单
				this.permissionsForm.menuIds = this.permissionsForm.menuIds.toString()
				this.permissionsForm.premisIds = this.permissionsForm.premisIds.toString()
				update(this.permissionsForm)
					.then((res) => {
						if (res.code == 200) {
							this.PermissionsFormVisible = false;
							this.permissionsForm = {}
							this.getDatailist();
						}
					})
			},
			//添加修改
			submitForm(formName) {

				if (this.upstatus) {

					update(this.form)
						.then((res) => {

							if (res.code == 200) {
								this.iustatus = false;
								this.upstatus = false;
								this.getDatailist();
								this.form = {}
							} else {
								this.logining = false
							}
						})

				} else {
					this.$refs[formName].validate((valid) => {
						if (valid) {
							insert(this.form)
								.then((res) => {

									if (res.code == 200) {
										this.getDatailist();
										this.iustatus = false;
										this.form = {}
									} else {}
								})

						} else {
							console.log('error submit!!');
							return false;
						}
					});
				}

			},

			//重置
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},

			//查询
			getDatailist() {
				list(this.tableParams)
					.then((res) => {
						if (res.code == 200) {
							this.tableData = res.data.records
							this.tableParams.pageNum = res.data.current, // 当前页码
								this.tableParams.pageSize = res.data.size
							this.tableParams.total = res.data.total
						} else {
							this.logining = false
						}
					})
			},
			onPageSizeChange(newPageSize) {
				// 更新每页显示的数量
				this.tableParams.pageSize = newPageSize;
				// 如果需要，可以在这里执行API调用来获取新的数据
			},
			onCurrentPageChange(newPageNum) {
				// 更新当前页码
				this.tableParams.pageNum = newPageNum;
				// 如果需要，可以在这里执行API调用来获取新的数据
			},

		}
	}
</script>
<style>
	.scrollable-table {
		height: 300px;
		overflow-y: auto;
		table-layout: auto;
		/* 取消固定布局 */
	}
</style>